package com.abu.auth.controller;

import com.abu.auth.config.JwtProperties;
import com.abu.auth.service.AuthService;
import com.abu.common.CookieUtils;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthDingTalkRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/oauth")
public class RestAuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback/ding")
    public ResponseEntity<Void> login(
            AuthCallback callback,
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse
    ) {
        AuthResponse response = getAuthRequest().login(callback);
        String token = this.authService.checkLogin(response);
        CookieUtils.setCookie(httpServletRequest, httpServletResponse, jwtProperties.getCookieName(), token, jwtProperties.getExpire() * 15);
        return ResponseEntity.ok().build();
    }

    private AuthRequest getAuthRequest() {
        return new AuthDingTalkRequest(AuthConfig.builder()
                .clientId("dingoabl82mkniu3acvfkv")
                .clientSecret("kYxv-2GwiQuVflkc7fd75uRKOV-gCJtDYUsgMS73-6TyvicrTtNKJmWAuSsF9CCRNr")
                .redirectUri("http://www.abu.com/oauth/callback/ding")
                .build());
    }
}
